package com.erp.controller;

import com.erp.mapper.GoodsMapper;
import com.erp.mapper.GoodsTypeMapper;
import com.erp.mapper.ShoplistMapper;
import com.erp.pojo.Goods;
import com.erp.pojo.Shoplist;
import com.erp.tool.ImportExcelUtils;
import com.erp.tool.OutExcelUtils;
import com.erp.tool.PgTool;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class ShopListController {

    @Autowired
    private ImportExcelUtils excelUtils;

    @Autowired
    private ShoplistMapper mapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OutExcelUtils outExcelUtils;

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    @RequestMapping("/uploadExcel")
    public Map<String,Object> upload(MultipartFile excelFile) throws Exception{
        Map<String,Object> map = new HashMap<>();
        if (excelFile.isEmpty()){
            map.put("mag","文件夹为空，重新上传");
            return map;
        }else {
            String fileName = excelFile.getOriginalFilename();
            InputStream is = excelFile.getInputStream();
            List<Shoplist> shopList = excelUtils.upload(fileName, is);
            if (mapper.insertShopList(shopList)>0){
                map.put("msg","数据添加成功");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String date=simpleDateFormat.format(new Date());
                map.put("data",mapper.conditionDate(date));
                return map;
            }else {
                map.put("msg","数据添加失败，请重新添加");
                return map;
            }
        }
    }


    @RequestMapping("/downloadExcel")
    public void downloadExcel(HttpServletResponse response,String date){
        XSSFWorkbook wb =outExcelUtils.show(mapper.conditionDate(date));
        String fileName = "采购计划.xlsx";
        OutputStream outputStream =null;
        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
            //设置ContentType请求信息格式
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/limitShopList")
    public List limitUsers(String date, int num,Integer state){
        System.out.println(state);
        List<Object>allList = new ArrayList<Object>();
        int row=4;
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("date",date);
        map.put("state",state);
        map.put("end",row);
        map.put("start", PgTool.getStart(num,row).get("start"));
        //查询需多少页
        allList.add(PgTool.getPage(row, mapper.countShopList(map)));
        //得到分页数据
        allList.add(mapper.findAllShopList(map));
        return allList;
    }

    @RequestMapping("/updateShopState")
    public Map updateShopState(Integer state,Integer id){
        Map<String, Boolean>map=new HashMap<>();
        if (mapper.updateShopState(state, id)>0){
            map.put("state",true);
        }else {
            map.put("state",false);
        }
        return map;
    }

    @RequestMapping ("/updateShopStateByIds")
    public Map updateShopStateByIds(Integer state,String idStr){
        String[] array=idStr.split("/");
        List<Integer>ids=new ArrayList<>();
        for (int i = 1; i < array.length; i++) {
            ids.add(Integer.parseInt(array[i]));
        }
        Map<String, Boolean>map=new HashMap<>();
        for (Integer id : ids) {
            System.out.println(id);
        }
        if (mapper.updateShopStateByIds(state, ids)>0){
            List<Shoplist> shoplists = mapper.findShopBuIDs(ids);
            List<Goods>goodsList=new LinkedList<>();
            for (Shoplist shoplist : shoplists) {
                Goods goods=new Goods(null,shoplist.getShopName(),"很棒！",null,new BigDecimal(String.valueOf(shoplist.getShopPrice())),null,shoplist.getShopNum(),new Date(),null,goodsTypeMapper.conditionalByName(shoplist.getShopType()),1);
                goodsList.add(goods);
            }
            goodsMapper.insertGoods(goodsList);
            map.put("state",true);
        }else {
            map.put("state",false);
        }
        return map;
    }
}
